import React, { useEffect, useState } from 'react';
import {
  Table, Modal, Form, Input, Col, message, Switch, Select,
} from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import RenderButtom from '@/components/RenderButton';
import SearchBox from '@/components/SearchBox'
import {
  deleteShopCat,
  fetchBusinessList, getBusinessById, saveShopCat,
} from '@/services/rentCenter/basicSet';
import { connect } from 'dva';
import { formItemLayout } from '@/utils/utils';

const hasSearchBtn = JSON.parse(localStorage.getItem('hasSearchBtn'))
const { Option } = Select

const columns = [
  {
    title: '序号',
    dataIndex: 'index',
    key: 'index',
  },
  {
    title: '业态编号',
    key: 'businessNumber',
  },
  {
    title: '业态名称（类别）',
    key: 'businessName',
  },
  {
    title: '状态',
    key: 'status',
    render: params => (
      <span>{params.status === '1' ? '启用' : '禁用'}</span>
    ),
  },
  {
    title: '创建时间',
    key: 'createTime',
  },
];

const storeShopFormats = props => {
  const { getFieldDecorator } = props.form;
  const [data, setColData] = useState([]);
  const [record, setRecord] = useState([]);
  const [firstId, setfirstId] = useState([]);
  const [listQuery, setListQuery] = useState({
    pageNo: 1,
    pageSize: 10,
  });
  const [info, setInfo] = useState({
    status: '1',
  });
  const [showtype2, setshowtype2] = useState(false);
  const [types, settypes] = useState([]);
  const [types2, settype2s] = useState([]);
  // 分配\新增角色模态框
  const [isShow, setState] = useState(false);

  // 列表
  const getList = async params => {
    const r = await fetchBusinessList(params);
    if (r.data && r.data.data) {
      setColData(r.data.data);
    }
    if (r.data && r.data.length) {
      settypes(r.data)
    }
  };
  useEffect(() => {
    getList(listQuery);
  }, []);

  // 查询
  const searchOneBtn = async params => {
    getList(params);
  };

  const removeRole = async record => {
    deleteShopCat({
      id: record.id,
    }).then(res => {
      if (res.data.code === '0') {
        const index = data.findIndex(e => e.id === record.id);
        setColData(() => {
          data.splice(index, 1);
          return [...data];
        });
      }
    })
  };
  // 新增/修改 模态框
  const handleStatus = record => {
    setState(!isShow);
    if (record) {
      setInfo(record)
    }
  };
  const getType2 = () => {
    getBusinessById({ id: listQuery.catId }).then(r => {
      if (r.data.code === '0') {
        if (listQuery.catId !== 0) {
          settype2s(r.data.data)
        } else {
          settypes(r.data.data)
        }
      }
    })
  }
  const typeChange = v => {
    setfirstId(v)
    if (v) {
      if (!types2) {
        setshowtype2(true)
      }
      getType2()
    } else {
      settype2s([])
      setshowtype2(false)
    }
  }
  // 查询表单
  const getFields = () => (
    <Col span={18}>
      <Col span={8}>
        <Form.Item label="模糊条件">
          <Input onChange={v => { setListQuery({ ...listQuery, condition: v.target.value }) }} value={listQuery.condition} placeholder="业态编号，类别" />
        </Form.Item>
      </Col>
      <Col span={8}>
        <Form.Item label="类别">
          <Select onChange={typeChange} value={firstId} placeholder="请选择一级业态">
            { types.map(v => (<Option key={v.id}>{v.businessName}</Option>)) }
          </Select>
          {
            showtype2 ? (<Select onChange={v => { setListQuery({ ...listQuery, catId: v }) }} value={listQuery.catId} placeholder="请选择二级业态">
              {types2.map(v => (<Option key={v.id}>{v.businessName}</Option>))}
            </Select>) : ''
          }
        </Form.Item>
      </Col>
      <Col span={8}>
        <Form.Item label="状态">
          <Select value={listQuery.status} placeholder="选择状态" onChange={v => { setListQuery({ ...listQuery, status: v }) }} >
            <Option key="1" value="1">启用</Option>
            <Option key="0" value="0">禁用</Option>
          </Select>
        </Form.Item>
      </Col>
    </Col>
  );
  // 查询表单逻辑
  const handleSearch = e => {
    e.preventDefault()
    searchOneBtn(listQuery);
  };

  // 表单提交
  const handleSubmit = e => {
    e.preventDefault();
    props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        let params = values
        params.status ? params.status = '1' : params.status = '0'
        console.log('Received values of form: ', values);
        saveShopCat({ storeBusiness: params }).then(() => {
          getList(listQuery)
          setState(!isShow);
        })
      }
    });
  };
  // 清空查询条件
  const handleReset = () => {
    setListQuery({
      pageNo: 1,
      pageSize: 10,
    })
    setfirstId('')
    setshowtype2(false)
    getList({
      pageNo: 1,
      pageSize: 10,
    })
  };
  // 按钮逻辑
  const handleBtn = type => {
    if (record.length !== 1 && type !== 1) return message.warning('请勾选一条数据！');
    switch (type) {
      // 新增
      case 1:
        return handleStatus();
      // 查询
      case 2:
        return handleSearch();
      case 3:
        return handleStatus(record[0]);
      // 删除
      case 4:
        return removeRole(record[0]);
      default:
        return ''
    }
  };
  const rowSelection = {
    type: 'radio',
    onChange: (selectedRowKeys, selectedRows) => {
      setRecord(selectedRows)
    },
  };
  return (
    <PageHeaderWrapper>
      {/* 查询条件 */}
      <SearchBox handleReset={handleReset} handleSearch={handleSearch} getFields={getFields} />
      <RenderButtom click={handleBtn} />
      <Table columns={columns} dataSource={hasSearchBtn ? data : data} rowSelection={rowSelection} rowKey={record => record.id} />
      {/* 新增/修改 */}
      <Modal
        title="新增/修改"
        visible={isShow}
        onOk={handleSubmit.bind(this)}
        onCancel={handleStatus.bind(this)}
        destroyOnClose
      >
        <Form {...formItemLayout}>
          <Form.Item label="业态名称">
            {getFieldDecorator('businessName', {
              initialValue: info.businessName || '',
              rules: [
                {
                  required: true,
                  message: '请输入业态名称',
                },
              ],
            })(<Input placeholder="请输入业态名称" />)}
          </Form.Item>
          <Form.Item label="上级分类">
            {getFieldDecorator('parentId', {
              initialValue: info.parentId || '',
              rules: [
                {
                  required: true,
                  message: '请选择上级',
                },
              ],
            })(<Select placeholder="请选择上级"><Option key="0" value="0">顶级分类</Option>{types.map(v => (<Option key={v.id}>{v.businessName}</Option>))}</Select>)}
          </Form.Item>
          <Form.Item label="状态">
            {getFieldDecorator('status', {
              initialValue: info && info.status === '1',
              valuePropName: 'checked',
              rules: [
                {
                  required: true,
                  message: '请选择状态',
                },
              ],
            })(<Switch />)}
          </Form.Item>
        </Form>
      </Modal>
    </PageHeaderWrapper>
  );
};
export default connect(({ role, global }) => ({
  role,
  hasSearchBtn: global.hasSearchBtn,
}))(Form.create()(storeShopFormats));
